package com.firewolf.vue.security;

import com.firewolf.vue.pojo.Menu;
import com.firewolf.vue.pojo.User;
import com.firewolf.vue.service.MenuService;
import com.firewolf.vue.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/3/7
 **/
public class LXUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        try {
            User u = userService.findUserByName(username); //根据用户名查询用户信息
            LXUser lxUser = new LXUser();

            List<Menu> menuList = menuService.findMenusByUserName(username); //根据用户名来查找菜单
            List<GrantedAuthority> authorities = new ArrayList<>();
            getAuthorities(menuList,authorities);
            lxUser.setAuthorities(authorities);
            BeanUtils.copyProperties(lxUser, u);
            lxUser.getAuthorities();
            return lxUser;
        } catch (Exception e) {
            throw new UsernameNotFoundException("账号不存在");
        }
    }


    private void getAuthorities(List<Menu> menus, List<GrantedAuthority> authorities) {
        if (CollectionUtils.isNotEmpty(menus)) {
            for (Menu m : menus) {
                if (StringUtils.isNotEmpty(m.getPerms())) {
                    authorities.add(new SimpleGrantedAuthority(m.getPerms()));
                }
                getAuthorities(m.getChildren(), authorities);
            }
        }
    }
}
